package water.service.impl;

import app.nbdevices.utils.ConvertUtil;
import ele.dto.SumDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import water.dto.DataDto;
import water.entity.WaterCycleReport;
import water.faultHandler.WaterFaultHandler;
import water.modle.codecModle.WaterReport;
import water.modle.revModle.RevWaterReportData;
import water.service.IWaterCycleReportService;
import water.service.IWaterService;
import water.utils.WaterDataDecode;
import water.utils.WaterExplain;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service("WaterService")
public class WaterService implements IWaterService {

    @Autowired
    @Qualifier("WaterCycleReportService")
    IWaterCycleReportService svcWaterCycle;

    @Autowired
    WaterFaultHandler waterFaultHandler;

    @Override
    public boolean saveWaterCycleData(RevWaterReportData revWaterReportData, String devId) {
        WaterReport waterReport= WaterDataDecode.WaterReportDataDecode(revWaterReportData.getResData());
        WaterCycleReport waterCycleReport= WaterExplain.exEleCycle(waterReport);
        waterCycleReport.setInternetDeviceId(devId);
        waterCycleReport.setWaterCmdCode(revWaterReportData.getCommand());
        waterCycleReport.setAddrId(revWaterReportData.getMeterAddr());
        waterFaultHandler.mainHandler(waterCycleReport);
        return svcWaterCycle.save(waterCycleReport);
    }

    @Override
    public List<DataDto> getWaterDataByTime(int t,String internetDevId) {
        //获取年月日
        int[] dayMonYear = WaterExplain.
                getDayMonYear(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        List<DataDto> res=null;
        if(t==0){
            List<DataDto> waterData=svcWaterCycle.getWaterDataByDay(internetDevId,dayMonYear[0]);
            res=new LinkedList<>();
            for(int i=0;i<waterData.size()-1;i++){
                DataDto dataDto=new DataDto();
                dataDto.setTime(waterData.get(i+1).getTime());
                dataDto.setCha(waterData.get(i).getCha()-waterData.get(i+1).getCha());
                res.add(0,dataDto);
            }
        }else if(t==1){
            res=svcWaterCycle.getWaterDataByMonth(internetDevId,dayMonYear[1]);
        }else{
            res=svcWaterCycle.getWaterDataByYear(internetDevId,dayMonYear[2]);
        }
        return res;
    }

    @Override
    public List<SumDto> getWaterSum() {
        int[] dayMonYear = WaterExplain.
                getDayMonYear(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        return svcWaterCycle.getSumWaterData(dayMonYear[0]);
    }



}
